<#include "../include/header.html">
<script type="text/javascript">

    var p_headerId = '${RequestParameters.headerId!0}';
    var viewModel = kendo.observable({
        model: {},
        create: function () {
            $('#grid').data('kendoGrid').addRow();
        },
        saveHead: function () {
            if (validator.validate()) {
                Hap.submitForm({
                    url: '${base.contextPath}/hap/om/order/headers/submit_head',
                    formModel: viewModel.model,
                    grid: {"omOrderLines": $("#grid")},
                    success: function (data) {
                    }
                });
            }
        },
        save: function () {
            if (validator.validate()) {
                Hap.submitForm({
                    url: '${base.contextPath}/hap/om/order/headers/submit',
                    formModel: viewModel.model,
                    grid: {"omOrderLines": $("#grid")},
                    success: function (data) {
                        $('#grid').data('kendoGrid').refresh();
                    }
                });
            }
        },
        printPDF: function () {
            if (validator.validate()) {
                Hap.submitForm({
                    url: '${base.contextPath}/hap/om/order/headers/printPDF',
                    formModel: viewModel.model,
                    grid: {"omOrderLines": $("#grid")},
                    success: function (data) {
                        $('#grid').data('kendoGrid').refresh();
                    }
                });
            }
        },
        close: function () {
            closeWin();
        },
        remove:function(){
            Hap.deleteGridSelection({
                grid: $("#grid")
            });
        },
        deleteAll: function () {
            if (validator.validate()) {
                Hap.submitForm({
                    url: '${base.contextPath}/hap/om/order/headers/deleteAll',
                    formModel: viewModel.model,
                    grid: {"omOrderLines": $("#grid")},
                    success: function (data) {
                        window.parent.viewModel.refresh();
                        closeWin();
                    }
                });
            }
        },
    });
    <#if RequestParameters.headerId??>
    Hap.loadViewModel({
        url:'${base.contextPath}/hap/om/order/headers/query?headerId=${RequestParameters.headerId!0}',
        model:viewModel.model
    });
    </#if>
    function closeWin() {
        window.parent.viewModel.refresh();
        window.parent.$('#dialog').data("kendoWindow").close();
    }
</script>
<body>
    <script src="${base.contextPath}/common/code?fndOrderStatus=FND_ORDER_STATUS" type="text/javascript"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/jszip/2.4.0/jszip.js"></script>
    <script src="${base.contextPath}/lib/bootstrap-3.3.7/js/bootstrap.min.js"></script>
    <script src="http://kendo.cdn.telerik.com/2015.3.1111/js/pako_deflate.min.js"></script>
    <div id="page-content">
        <div class="panel" id="inQuery" style="padding: 0px;border:none;box-shadow: none;">
            <form class="form-horizontal" id="myForm">
                <div class="panel-body">

                    <div class="row">

                        <div class="col-sm-4">
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.orderNumber"/></label>
                                <div class="col-sm-8">
                                    <input id='orderNumber' type="text" disabled="true" style="width: 100%"
                                    data-bind="value:model.orderNumber">
                                </div>
                            </div>
                        </div>

                        <div class="col-sm-4">
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.companyId"/></label>
                                <div class="col-sm-8">
                                    <input id='companyId' disabled="true" type="text" style="width: 100%" data-bind="value:model.companyId">
                                    <script>
                                        $("#companyId").kendoLov($.extend(<@lov "LOV_FND_COMPANY"/>, {
                                            textField: 'companyName',
                                            model: viewModel.model
                                        }));
                                    </script>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.customerId"/></label>
                                <div class="col-sm-8">
                                    <input id='customerId' disabled="true" type="text" style="width: 100%" data-bind="value:model.customerId">
                                    <script>
                                        $("#customerId").kendoLov($.extend(<@lov "LOV_FND_CUSTOMER"/>, {
                                            textField: 'customerName',
                                            model: viewModel.model
                                        }));
                                    </script>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">

                        <div class="col-sm-4">
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.orderDate"/></label>
                                <div class="col-sm-8">
                                    <input id='orderDate' type="text" style="width: 100%" data-bind="value:model.orderDate" data-role="datepicker" required data-label="<@spring.message 'OmOrderHeaders.orderDate'/>" disabled="true">
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.account_money"/></label>
                                <div class="col-sm-8">
                                    <input id='account_money' type="text" style="width: 100%" data-bind="value:model.account_money" disabled="true">
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-sm-4">
                            <div class="form-group">
                                <label class="col-sm-4 control-label"><@spring.message "OmOrderHeaders.orderStatus"/></label>
                                <div class="col-sm-8">
                                    <input id='orderStatus' disabled="true" type="text" style="width: 100%" data-bind="value:model.orderStatus">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="pull-left" id="query-form" style="padding-bottom:10px;">
                        <button id="saveHead" class="btn btn-primary" style="float:left;" data-bind="click:saveHead"
                        type="button"><i class="fa fa-save" style="margin-right: 3px;"></i> <@spring.message "hap.save"/></button>
                        <#if accessService.access('submit')>
                        <button id="submit" class="btn btn-primary" style="margin-left: 10px" onclick="submitApprove('SUBMITED')"
                        type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.submit"/></button>
                        </#if>
                        <#if accessService.access('approve')>
                        <button id="approve" class="btn btn-primary" style="margin-left: 10px" onclick="submitApprove('APPROVE')"
                        type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.approve"/></button>
                        </#if>
                        <#if accessService.access('reject')>
                        <button id="reject" class="btn btn-primary" style="margin-left: 10px" onclick="submitApprove('REJECTED')"
                        type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.reject"/></button>
                        </#if>
                        <button id="deleteAll" class="btn btn-primary" style="margin-left: 10px" data-bind="click:deleteAll"
                        type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.delectAll"/></button>
                        <button id="print" class="btn btn-primary" style="margin-left: 10px" data-bind="click:printPDF"
                        type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.printExcel"/></button>
                        <button id="close" class="btn btn-primary" style="margin-left: 10px" data-bind="click:close"
                        type="button"><i class="fa fa-eraser" style="margin-right:3px;"></i><@spring.message "hap.goBack"/></button>
                    </div>
                </div>
            </form>

        </div>
        <div id="my_panel">
            <ul class="nav nav-tabs" id="mytab">
                <li class="active"><a href="#maintain" data-toggle="tab"><@spring.message "main.info"/></a></li>
                <li class=""><a href="#showTreeUnit" data-toggle="tab"><@spring.message "other.info"/></a></li>
            </ul>
            <div id="tabContent" class="tab-content">
                <div class="tab-pane fade in active" style="margin-top: 10px;" id="maintain">
                    <div class="pull-left" id="toolbar-btn" style="padding-bottom:10px;">
                        <span class="btn btn-primary k-grid-add" style="float:left;margin-right:5px;" data-bind="click:create"><@spring.message "hap.new"/></span>
                        <span class="btn btn-success k-grid-save-changes" data-bind="click:save" style="float:left;margin-right:5px;"><@spring.message "hap.save"/></span>
                        <!--<span  data-bind="click:remove" class="btn btn-danger" style="float:left;"><@spring.message "hap.delete"/></span>-->
                        <span onclick="deleteData()" class="btn btn-danger" style="float:left;"><@spring.message "hap.delete"/>
                    </div>
                    <script>kendo.bind($('#toolbar-btn'), viewModel);</script>
                    <!-- <div class="pull-right" id="query-form" style="padding-bottom:10px;">
                        <span class="btn btn-primary" style="float:left;width:70px" data-bind="click:query" type="submit"><@spring.message "hap.query"/></span>
                        <div style="clear:both"></div>
                    </div>
                    <script>kendo.bind($('#query-form'), viewModel);</script> -->
                    <div style="clear:both">
                        <div id="grid"></div>
                    </div>
                </div>
                <div id="showTreeUnit" class="tab-pane fade">
                    <div>
                        <!--<div class="pull-left" id="toolbar-btn1" style="padding-bottom:10px;">-->
                        <!--<button class="btn btn-primary k-grid-add" style="float:left;margin-right:5px;" data-bind="click:create"><@spring.message "hap.new"/></button>-->
                        <!--<button class="btn btn-success k-grid-save-changes" data-bind="click:save" style="float:left;margin-right:5px;"><@spring.message "hap.save"/></button>-->
                        <!--<button onclick="deleteData()" class="btn btn-danger" style="float:left;"><@spring.message "hap.delete"/></button>-->
                        <!--</div>-->
                    </div>
                    <script>kendo.bind($('#toolbar-btn1'), viewModel);</script>
                    <div style="clear:both">
                        <div id="treeGrid" ></div>
                    </div>
                </div>
            </div>
        </div>
        <script type="text/javascript">
            kendo.bind($('#myForm'), viewModel);
            var validator = $("#myForm").kendoValidator({
                invalidMessageType : "tooltip"
            }).data("kendoValidator");
            //Hap.initEnterQuery('#query-form', viewModel.query);
            var BaseUrl = _basePath;
            dataSource = new kendo.data.DataSource({
                transport: {
                    read: {
                        url: BaseUrl + "/hap/om/order/lines/query",
                        type: "POST",
                        dataType: "json"
                    },
                    update: {
                        url: BaseUrl + "/hap/om/order/lines/submit",
                        type: "POST",
                        contentType: "application/json"
                    },
                    destroy: {
                        url: BaseUrl + "/hap/om/order/lines/remove",
                        type: "POST",
                        contentType: "application/json"
                    },
                    create: {
                        url: BaseUrl + "/hap/om/order/lines/submit",
                        type: "POST",
                        contentType: "application/json"
                    },
                    parameterMap: function (options, type) {
                        if (type !== "read" && options.models) {
                            var datas = Hap.prepareSubmitParameter(options, type)
                            return kendo.stringify(datas);
                        } else if (type === "read") {
                            var param1={};
                            param1["headerId"]=p_headerId;
                            var qy=Hap.prepareQueryParameter(param1, options)
                            return qy;
                        }
                    }
                },
                batch: true,
                serverPaging: true,
                pageSize: 10,
                schema: {
                    data: 'rows',
                    total: 'total',
                    model: {
                        id: "lineId",
                        fields: {
                            inventoryItemId:{
                                validation:{
                                    required: true    
                                }
                            },
                            itemDescription:{
                                validation:{
                                    required: true    
                                }
                            },
                            itemUom:{
                                validation:{
                                    required: true    
                                }
                            },
                            orderdQuantity:{
                                validation:{
                                    required: true    
                                }
                            },
                            unitSellingPrice:{
                                validation:{
                                    required: true    
                                }
                            },
                            description:{
                                validation:{
                                    required: true    
                                }
                            },
                        },
                        editable:function (col) {
                            if(col=='lineNumber'){
                                return false;
                            }
                            if(col=='amount'){
                                return false;
                            }
                            return true;
                        }
                    }
                }
            });

            var orderGrid = $("#grid").kendoGrid({
                dataSource: dataSource,
                resizable: true,
                scrollable: true,
                navigatable: false,
                selectable: 'multiple, rowbox',
                //autoBind:<#if RequestParameters.headerId??> true <#else> false</#if>,
                dataBound: function () {
                    if (parent.autoResizeIframe) {
                        parent.autoResizeIframe('${RequestParameters.functionCode!}')
                    }
                },
                pageable: {
                    pageSizes: [5, 10, 20, 50],
                    refresh: true,
                    buttonCount: 5
                },
                columns: [
            /*
            {
                field: "lineId",
                title: '<@spring.message "OmOrderLines.lineId"/>',
                width: 120
            },
                    {
                field: "headerId",
                title: '<@spring.message "OmOrderLines.headerId"/>',
                width: 120
            },
            */
            {
                field: "lineNumber",
                title: '<@spring.message "OmOrderLines.lineNumber"/>',
                width: 55,
            },
            {
                field: "inventoryItemId",
                title: '<@spring.message "OmOrderLines.inventoryItemId"/>',
                width: 120,
                template: function (dataItem) {
                    return dataItem['itemCode'] || ''
                },
                editor: function (container, options) {
                    $('<input name="' + options.field + '"/>')
                    .appendTo(container)
                    .kendoLov($.extend(<@lov "LOV_FND_INV_CODE"/>, {
                        textField: 'itemCode',
                        model: options.model,
                        select: function(e) {
                            options.model.set('itemCode', e.item.itemCode);
                            options.model.set('itemDescription', e.item.itemDescription);
                            options.model.set('itemUom', e.item.itemUom);
                        },
                        change: function(e) {
                            if (e.sender._prev == '' || e.sender._prev == null) {
                                options.model.set('itemCode', '');
                                options.model.set('itemDescription', '');
                                options.model.set('itemUom', '');
                            }
                        }
                    }));
                }
            },
            {
                field: "itemDescription",
                title: '<@spring.message "OmOrderLines.itemDescription"/>',
                width: 120,
            },
            {
                field: "itemUom",
                title: '<@spring.message "OmOrderLines.itemUom"/>',
                width: 120,
            },
//            {
//                field: "orderQuantityUom",
//                title: '<@spring.message "OmOrderLines.orderQuantityUom"/>',
//                width: 120
//            },
{
    field: "orderdQuantity",
    title: '<@spring.message "OmOrderLines.orderdQuantity"/>',
    width: 120
},

{
    field: "unitSellingPrice",
    title: '<@spring.message "OmOrderLines.unitSellingPrice"/>',
    width: 120
},
{
    field: "amount",
    title: '<@spring.message "OmOrderLines.amount"/>',
    width: 120
},
{
    field: "description",
    title: '<@spring.message "OmOrderLines.description"/>',
    width: 120
},
            /*
                    {
                field: "companyId",
                title: '<@spring.message "OmOrderLines.companyId"/>',
                width: 120
            },
            */
            /*
                    {
                field: "addition1",
                title: '<@spring.message "OmOrderLines.addition1"/>',
                width: 120
            },
                    {
                field: "addition2",
                title: '<@spring.message "OmOrderLines.addition2"/>',
                width: 120
            },
                    {
                field: "addition3",
                title: '<@spring.message "OmOrderLines.addition3"/>',
                width: 120
            },
                    {
                field: "addition4",
                title: '<@spring.message "OmOrderLines.addition4"/>',
                width: 120
            },
                    {
                field: "addition5",
                title: '<@spring.message "OmOrderLines.addition5"/>',
                width: 120
            },
            */
            ],
            editable: false
        });
$("#orderStatus").kendoComboBox({
    dataSource: fndOrderStatus,
    valuePrimitive: true,
    dataTextField: "meaning",
    dataValueField: "value"
});
function deleteData() {
    var selections = orderGrid.data("kendoGrid").selectedDataItems();
    var selections_tree = treeGrid.data("kendoGrid").selectedDataItems();
    if(selections.length==0 && selections_tree.length == 0){
        kendo.ui.showInfoDialog({
            message: $l('hap.tip.selectrows')
        });
        return;
    }
    if(selections.length == 0 || selections == null) {
        selections = selections_tree;
    }
    $.ajax({
        url: _basePath+'/hap/om/order/lines/remove',
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: kendo.stringify(selections),
        success: function (args) {
            if(args.success==true){
                orderGrid.data("kendoGrid").dataSource.page(1);
            }else{
                kendo.ui.showErrorDialog({
                    width: 600,
                    message: args.message
                });
            }
        }
    });
};

var treeGrid = $("#treeGrid").kendoGrid({
    dataSource: dataSource,
    resizable: true,
    scrollable: true,
    navigatable: false,
    selectable: 'multiple, rowbox',
            //autoBind:<#if RequestParameters.headerId??> true <#else> false</#if>,
            dataBound: function () {
                if (parent.autoResizeIframe) {
                    parent.autoResizeIframe('${RequestParameters.functionCode!}')
                }
            },
            pageable: {
                pageSizes: [5, 10, 20, 50],
                refresh: true,
                buttonCount: 5
            },
            columns: [
            {
                field: "lineNumber",
                title: '<@spring.message "OmOrderLines.lineNumber"/>',
                width: 55,
            },
            {
                field: "addition1",
                title: '<@spring.message "OmOrderLines.addition1"/>',
                width: 120
            },
            {
                field: "addition2",
                title: '<@spring.message "OmOrderLines.addition2"/>',
                width: 120
            },
            {
                field: "addition3",
                title: '<@spring.message "OmOrderLines.addition3"/>',
                width: 120
            },
            {
                field: "addition4",
                title: '<@spring.message "OmOrderLines.addition4"/>',
                width: 120
            },
            {
                field: "addition5",
                title: '<@spring.message "OmOrderLines.addition5"/>',
                width: 120
            },

            ],
            editable: false
        });
function submitApprove(status) {
    viewModel.model.orderStatus = status;
    Hap.submitForm({
        url: '${base.contextPath}/hap/om/order/headers/submit_head',
        formModel: viewModel.model,
        grid: {"omOrderLines": $("#grid")},
        success: function (data) {
            closeWin_dow();
            window.parent.viewModel.refresh();
        }
    })
}
function closeWin_dow() {
    window.parent.viewModel.refresh();
    window.parent.$('#dialog').data("kendoWindow").close();
}
if($("#orderStatus").val() == 'NEW') {
    $("#approve").attr("disabled","true");
    $("#reject").attr("disabled","true");
    $("#approve").attr("onclick","null");
    $("#reject").attr("onclick","null");
}
if($("#orderStatus").val() == 'SUBMITED') {

    $("#saveHead").attr("disabled","true");
    $("#submit").attr("disabled","true");
    $("#saveHead").attr("onclick","null");
    $("#submit").attr("onclick","null");
}
if($("#orderStatus").val() == 'APPROVE') {
    $("#saveHead").attr("disabled","true");
    $("#submit").attr("disabled","true");
    $("#approve").attr("disabled","true");
    $("#reject").attr("disabled","true");
    $("#deleteAll").attr("disabled","true");

    $("#saveHead").attr("onclick","null");
    $("#submit").attr("onclick","null");
    $("#approve").attr("onclick","null");
    $("#reject").attr("onclick","null");
    $("#deleteAll").attr("onclick","null");

}
if($("#orderStatus").val() == 'REJECTED') {
    console.log($("#orderStatus").val());
    $("#approve").attr("disabled","true");
    $("#reject").attr("disabled","true");

    $("#approve").attr("onclick","null");
    $("#reject").attr("onclick","null");
}
</script>
</body>
</html>